<?php
/**
 * Created by PhpStorm.
 * User: zhangrongxiang
 * Date: 2017/5/31
 * Time: 上午10:25
 */

$var1 = "Example variable";
$var2 = "";
$var3 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
        $GLOBALS["var3"] =& $var1; // visible also in global context
    }
    echo $var2 . PHP_EOL;
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
echo "var2 is set to '$var3'\n"; // var2 is set to 'Example variable'

//如果在一个函数内部给一个声明为 global 的变量赋于一个引用，该引用只在函数内部可见。
//可以通过使用 $GLOBALS 数组避免这一点。
//把 global $var; 当成是 $var =& $GLOBALS['var']; 的简写。
//从而将其它引用赋给 $var 只改变了本地变量的引用。
//print_r($GLOBALS);